package com.example.web_chat.service;

import com.example.web_chat.mapper.UserMapper;
import com.example.web_chat.model.*;
import com.example.web_chat.toolsUtil.Constant;
import com.example.web_chat.toolsUtil.Secret;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Slf4j
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;
    //登录逻辑

    public Result loginLogic(String username, String password, HttpServletRequest request) {

        //校验参数
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.error("用户名或密码空");
            return Result.fail("用户名或密码为空");
        }
        //判断密码是否小于6位
        if(password.length() < 6) {
            return Result.fail("用户不存在");
        }
        //查询数据库
        User user = userMapper.selectUser(username);
        if(user == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        // TODO 校验密码
        boolean ret = Secret.verifyPassword(password, user.getPassword());
        if (!ret) {
            log.error("密码错误");
            return Result.fail("密码错误");
        }
        //创建session
        HttpSession session = request.getSession(true);
        session.setAttribute(Constant.USER_SESSION, user);
        return Result.success();
    }

    //用户注册逻辑
    public Result registerLogic(String username, String password) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.error("用户名或密码为空");
            return Result.fail("用户名或密码为空");
        }
        if(password.length() < 6) {
            log.error("密码不符合要求");
            return Result.fail("密码不符合要求");
        }
        //检查用户名在数据库中是否存在
        User user = userMapper.selectUser(username);
        if(user != null) {
            log.error("用户名已经存在");
            return Result.fail("用户名已经存在");
        }
        //TODO:密码加密
        String finalPassword = Secret.addSecret(password);
        //存入数据库
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(finalPassword);
        Integer ret = userMapper.insertUser(newUser);
        if(ret < 1) {
            return Result.fail("注册失败");
        }
        return Result.success();
    }

    public Result  getUserInfo(HttpServletRequest request) {
        /*
        步骤：
        1. 先从请求中获取到会话
        2. 再从会话中获取到登录的对象
         */

        //从session中获取
        HttpSession session = request.getSession(false);
        if(session == null) {
            log.error("session不存在");
            return Result.fail("session不存在");
        }
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        if(user == null) {
            log.error("user不存在");
            return Result.fail("user不存在");
        }
        log.info("user:{}", user);
        return Result.success(user);
    }

    public Result getFriendLogic(HttpServletRequest request) {
        //从session中取出userId
        HttpSession session = request.getSession(false);
        if(session == null) {
            log.error("session不存在");
            return Result.fail("session不存在");
        }
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        if(user == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        Integer userId = user.getUserId();
        List<Friend> friends = userMapper.queryFriend(userId);
        log.info("friend:{}", friends);
        return Result.success(friends);
    }

    //获取session列表逻辑
    public Result getSessionLogic(HttpServletRequest request) {
        //1. 获取到session中的userId

        //2. 根据userId获取当前用户都有哪些会话

        //3. 根据sessionId获取当前会话中都有哪些好友信息

        //4. 返回该会话中最后一条消息

        //5. 返回响应
        HttpSession session = request.getSession(false);
        if(session == null) {
            log.error("session为空");
            return Result.fail("用户不存在");
        }
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        if(user == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        Integer userId = user.getUserId();
        //2. 根据userId获取当前用户都有哪些会话
        List<Integer> sessionIds = userMapper.querySessionIdByUserId(userId);
        List<MessageSession> messageSessionList = new ArrayList<>();

        for(Integer sessionId : sessionIds) {

            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);
            //3. 根据sessionId获取当前会话中都有哪些好友
            List<Friend> friends = userMapper.queryFriendBySessionId(sessionId, userId);
            messageSession.setFriends(friends);
            //4. 返回该会话中最后一条消息
            String lastMessageBySessionId = userMapper.getLastMessageBySessionId(sessionId);

            if(lastMessageBySessionId == null) {
                messageSession.setLastMessage("");
            }else {
                messageSession.setLastMessage(lastMessageBySessionId);
            }

            messageSessionList.add(messageSession);
        }

        return Result.success(messageSessionList);
    }

    //创建会话逻辑
    @Transactional
    public Result createSessionLogic(Integer friendId, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session == null) {
            log.error("session为空");
            return Result.fail("用户不存在");
        }
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        if(user == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        Integer userId = user.getUserId();
        MessageSession messageSession = new MessageSession();
        // 1.插入session数据库中,返回自增的sessionId
        userMapper.insertSession(messageSession);
        Integer retId = messageSession.getSessionId();
        log.info("返回的会话的自增id:{}", retId);

        // 2. 插入数据库,将用户id和会话id插入
        Integer integer = userMapper.insertMessageSessionUser(retId, userId);
        // 3. 插入数据库，将好友的id和会话id插入
        Integer integer1 = userMapper.insertMessageSessionUser(retId, friendId);

        if(retId == null || integer == null || integer1 == null) {

            return Result.fail("新增会话失败");
        }
        log.info("新增会话成功");
        Map<String, Integer> map = new HashMap<>();
        map.put("sessionId", retId);
        return Result.success(map);
    }

    //获取消息逻辑
    public Result getMessageLogic(Integer sessionId) {
        //查询数据库
        List<Message> allMessageForSession = userMapper.getAllMessageForSession(sessionId);
        if(allMessageForSession == null) {
            log.error("当前会话中没有消息");
            Result.fail("当前会话中没有消息");
        }
        log.info("指定会话中的所有消息:{}", allMessageForSession);
        //将即可中的元素逆序
        Collections.reverse(allMessageForSession);
        return Result.success(allMessageForSession);
    }
}
